import axios from 'axios'

export const streamChat = async ({ question, token }, callback) => {
  const controller = new AbortController()
  
  try {
    const response = await axios({
      method: 'post',
      url: 'http://localhost:8886/ai/sse',
      data: { question, token },
      responseType: 'stream',
      signal: controller.signal,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      }
    })

    const reader = response.data.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      
      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n\n')
      buffer = lines.pop() || ''
      
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          callback(line.slice(6)) // 去掉"data: "前缀
        }
      }
    }
    
  } catch (error) {
    if (!axios.isCancel(error)) {
      console.error('Stream request failed:', error)
      throw error
    }
  }
  
  return () => {
    controller.abort()
  }
}